package com.example.electricbicycle.dao;

import com.example.electricbicycle.po.Salesman;
import utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SalesmanDAO {
    public Salesman getSalesmanById(int id) throws SQLException {
        String sql = "SELECT * FROM user WHERE id = ?";
        try (Connection conn = DBUtils.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, id);
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    Salesman salesman = new Salesman();
                    salesman.setId(rs.getInt("id"));
                    salesman.setName(rs.getString("name"));
                    salesman.setPassword(rs.getString("password"));
                    return salesman;
                }
            }
        } catch (SQLException e) {
            System.err.println("获取业务员信息失败: " + e.getMessage());
            throw e;
        }
        return null;
    }

    public boolean updatePassword(int id, String newPassword) throws SQLException {
        String sql = "UPDATE user SET password = ? WHERE id = ?";
        try (Connection conn = DBUtils.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, newPassword);
            stmt.setInt(2, id);

            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            System.err.println("更新密码失败: " + e.getMessage());
            throw e;
        }
    }
}